import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Project } from '../../entities/project.entity';
import { Priority, ProjectStatus } from '../../types/enums';
import { User } from '../../entities/user.entity';
import { Workspace } from '../../entities/workspace.entity';
import { ProjectMember } from '../../entities/project-member.entity';
import { ProjectMemberRole, UserStatus } from '../../types/enums';

@Injectable()
export class ProjectService {
  constructor(
    @InjectRepository(Project)
    private projectRepository: Repository<Project>,
    @InjectRepository(Workspace)
    private workspaceRepository: Repository<Workspace>,
    @InjectRepository(User)
    private userRepository: Repository<User>,
    @InjectRepository(ProjectMember)
    private projectMemberRepository: Repository<ProjectMember>,
  ) {}

  async createProject(
    name: string,
    description: string,
    workspaceId: string,
    startDate: Date,
    endDate: Date,
    status: ProjectStatus = ProjectStatus.ACTIVE,
    priority: Priority = Priority.MEDIUM,
    userId: string,
  ): Promise<Project> {
    // 验证日期
    if (startDate >= endDate) {
      throw new BadRequestException('开始日期必须早于结束日期');
    }

    // 验证工作区是否存在
    const workspace = await this.workspaceRepository.findOne({ 
      where: { id: workspaceId } 
    });
    
    if (!workspace) {
      throw new NotFoundException('工作区不存在');
    }
    
    // 验证用户是否存在
    const user = await this.userRepository.findOne({ 
      where: { id: userId } 
    });
    
    if (!user) {
      throw new NotFoundException('用户不存在');
    }

    // 创建新项目
    const project = this.projectRepository.create({
      name,
      description,
      workspaceId,
      startDate,
      endDate,
      status,
      priority,
      createdById: userId
    });

    return this.projectRepository.save(project);
  }

  async getProjects(workspaceId?: string, status?: ProjectStatus): Promise<Project[]> {
    const queryBuilder = this.projectRepository.createQueryBuilder('project')
      .leftJoinAndSelect('project.createdBy', 'createdBy')
      .orderBy('project.createdAt', 'DESC');
    
    if (workspaceId) {
      queryBuilder.andWhere('project.workspaceId = :workspaceId', { workspaceId });
    }
    
    if (status) {
      queryBuilder.andWhere('project.status = :status', { status });
    } else {
      // 默认不显示已删除的项目
      queryBuilder.andWhere('project.status != :deletedStatus', { deletedStatus: ProjectStatus.DELETED });
    }
    
    return queryBuilder.getMany();
  }

  async getProjectById(id: string): Promise<Project> {
    const project = await this.projectRepository.findOne({ 
      where: { id },
      relations: ['createdBy']
    });
    
    if (!project) {
      throw new NotFoundException('项目不存在');
    }
    
    return project;
  }

  async updateProject(
    id: string,
    name?: string,
    description?: string,
    status?: ProjectStatus,
    priority?: Priority,
    startDate?: Date,
    endDate?: Date,
  ): Promise<Project> {
    const project = await this.getProjectById(id);
    
    // 更新字段
    if (name) project.name = name;
    if (description) project.description = description;
    if (status) project.status = status;
    if (priority) project.priority = priority;
    
    if (startDate) project.startDate = startDate;
    if (endDate) project.endDate = endDate;
    
    // 如果同时更新了开始和结束日期，需要验证
    if (startDate && endDate && startDate >= endDate) {
      throw new BadRequestException('开始日期必须早于结束日期');
    } else if (startDate && !endDate && startDate >= project.endDate) {
      throw new BadRequestException('开始日期必须早于结束日期');
    } else if (!startDate && endDate && project.startDate >= endDate) {
      throw new BadRequestException('开始日期必须早于结束日期');
    }
    
    return this.projectRepository.save(project);
  }

  async deleteProject(id: string): Promise<{ message: string }> {
    const project = await this.getProjectById(id);
    
    // 软删除 - 只更改状态
    project.status = ProjectStatus.DELETED;
    await this.projectRepository.save(project);
    
    return { message: '项目已删除' };
  }

  async hardDeleteProject(id: string): Promise<{ message: string }> {
    const project = await this.getProjectById(id);
    
    // 物理删除 - 实际从数据库中删除
    await this.projectRepository.remove(project);
    
    return { message: '项目已永久删除' };
  }

  /**
   * 获取项目成员列表
   */
  async getProjectMembers(projectId: string): Promise<ProjectMember[]> {
    // 验证项目是否存在
    await this.findProjectById(projectId);
    
    return this.projectMemberRepository.find({
      where: { projectId },
      relations: ['user'],
    });
  }

  /**
   * 添加项目成员
   */
  async addProjectMember(
    projectId: string, 
    userId: string, 
    role: ProjectMemberRole = ProjectMemberRole.MEMBER
  ): Promise<ProjectMember> {
    // 验证项目是否存在
    await this.findProjectById(projectId);
    
    // 验证用户是否存在
    const user = await this.userRepository.findOne({ 
      where: { id: userId } 
    });
    
    if (!user) {
      throw new NotFoundException('用户不存在');
    }
    
    // 检查用户是否已经是项目成员
    const existingMember = await this.projectMemberRepository.findOne({
      where: { projectId, userId }
    });
    
    if (existingMember) {
      throw new BadRequestException('用户已经是项目成员');
    }
    
    // 创建新成员
    const projectMember = this.projectMemberRepository.create({
      projectId,
      userId,
      role,
      joinedAt: new Date(),
      status: UserStatus.ACTIVE
    });
    
    return this.projectMemberRepository.save(projectMember);
  }

  /**
   * 更新项目成员信息
   */
  async updateProjectMember(
    projectId: string,
    userId: string,
    role: ProjectMemberRole,
    status?: UserStatus
  ): Promise<ProjectMember> {
    // 验证项目是否存在
    await this.findProjectById(projectId);
    
    // 查找成员
    const member = await this.projectMemberRepository.findOne({
      where: { projectId, userId }
    });
    
    if (!member) {
      throw new NotFoundException('项目成员不存在');
    }
    
    // 更新成员信息
    member.role = role;
    if (status) {
      member.status = status;
    }
    
    return this.projectMemberRepository.save(member);
  }

  /**
   * 移除项目成员
   */
  async removeProjectMember(projectId: string, userId: string): Promise<{ message: string }> {
    // 验证项目是否存在
    await this.findProjectById(projectId);
    
    // 查找成员
    const member = await this.projectMemberRepository.findOne({
      where: { projectId, userId }
    });
    
    if (!member) {
      throw new NotFoundException('项目成员不存在');
    }
    
    // 删除成员
    await this.projectMemberRepository.remove(member);
    
    return { message: '成员已移除' };
  }
  
  /**
   * 查找项目（内部方法）
   */
  private async findProjectById(id: string): Promise<Project> {
    const project = await this.projectRepository.findOne({ 
      where: { id } 
    });
    
    if (!project) {
      throw new NotFoundException('项目不存在');
    }
    
    return project;
  }
} 